package com.bigben.springbootshiro.config;

import com.bigben.springbootshiro.bean.User;
import com.bigben.springbootshiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权doGetAuthorizationInfo");
        //给用户授予权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的用户
        Subject subject= SecurityUtils.getSubject();
        //拿到user对象 切记下面管理密码的方法中要将第一个参数设置为user 不然会报java.lang.String cannot be cast to com.bigben.springbootshiro.bean.User
        User currentUser = (User) subject.getPrincipal();

        //从数据库中获得权限
        info.addStringPermission(currentUser.getPerms());


        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证doGetAuthorizationInfo");
        //与输入的数据想匹配u一般数据库中取

        UsernamePasswordToken usertoken=(UsernamePasswordToken) token;
        User user = userService.queryUserByName(usertoken.getUsername());


        //RedisSerializer redisSerializer = new StringRedisSerializer();
       // redisTemplate.setKeySerializer(redisSerializer);
        //user = (User) redisTemplate.opsForValue().get("allusers");
       // redisTemplate.opsForValue().set("allusers", user);


        
        //用户名认证
        if (user==null){
            return null;//会自动报出异常
        }



        //使用session判断用户是否登录
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("LoginUser",user);

        //密码认证
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");



    }
}
